package com.lanou3g.hw0512;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "searchServlet", urlPatterns = "/s")
public class searchServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf8");
        // 获取前端传过来的参数
        String keyword = request.getParameter("keyword");
        // 加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lanou_news", "root", "123456");

            String sql = "select * from my_news where title like " + "'%" + keyword + "%'";
            PreparedStatement statement = conn.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();

            PrintWriter pw = response.getWriter();

            while (rs.next()) {
                String t = rs.getString("title");
                response.getWriter().println(t);
                pw.println("<br/>");
            }
            rs.close();
            conn.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
